package net.qiqbframework.spring.messaging;

import net.qiqbframework.messaging.annotation.*;
import net.qiqbframework.common.utils.AnnotationUtil;
import org.springframework.core.ResolvableType;

import java.lang.reflect.Executable;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Collection;
import java.util.Map;

public class CollectionGenericsParameterResolverFactory implements HandlerParameterResolverFactory {


    @Override
    public HandlerParameterResolver createInstance(Executable executable, Parameter[] parameters, int parameterIndex) {
        Class<?> parameterType = parameters[parameterIndex].getType();
        if (parameterIndex == 0 ) {
            Class<?> payloadType = (Class<?>) AnnotationUtil.findAnnotationAttributes(executable, MessageHandler.class)
                    .map(attr -> attr.get("payloadType"))
                    .orElse(Object.class);
            //

            if (Collection.class.isAssignableFrom(parameterType)) {
                if (executable instanceof Method method) {
                    final ResolvableType resolvableType = ResolvableType.forMethodParameter(method, 0);
                    final ResolvableType generic = resolvableType.getGeneric(0);
                    if (payloadType.isAssignableFrom(parameterType) && generic.getType() instanceof Class<?>) {
                        return new CollectionPayloadParameterResolver((Class<?>) generic.getType());
                    }

                }
            }
            // 持久化修改特有
            if (Map.class.isAssignableFrom(parameterType)) {
                if (executable instanceof Method method) {
                    final ResolvableType resolvableType = ResolvableType.forMethodParameter(method, 0);
                    final ResolvableType generic = resolvableType.getGeneric(0);
                    return new MapPayloadParameterResolver((Class<?>) generic.getType());

                }
            }
        }
        return null;
    }
}
